package com.ksyzt.ksite2.server.listener.tasks;

import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ksyzt.ksite2.server.common.Application;
import com.ksyzt.ksite2.server.database.dao.IWATER_INFODAO;
import com.ksyzt.ksite2.server.database.dao.impl.WATER_INFODAOImpl;
import com.ksyzt.ksite2.shared.modle.WATER_INFOObj;

public class ZhuJiangWater extends TimerTask
{

     public static String water_url = "http://www.pearlwater.gov.cn/PearlwaterApps/zjsq_swz.js";

    /**
     * @param argsatic
     */
    public static void main(String[] args)
    {
	ZhuJiangWater app = new ZhuJiangWater();
	app.update();
	// String
	// text=Util.readTextFile("C:\\Documents and Settings\\Administrator\\桌面\\dtxad\\zjsq_swz.js","GB2312");
	// // text=new String(text.getBytes("iso-"),"GB2312");
	// System.out.println(text);
	// String t=app.findRow(text);
	// System.out.println(t);

    }

    public void update()
    {
	String data = getData();
	if (data.length() == 0)
	{
	    log("Error:" + "解析数据错误");
	} else
	{

	    String row = findRow(data);
	    WATER_INFOObj info = parseData(row);
	    if (info.getUPDATETIME() != null)
	    {
		IWATER_INFODAO dao = new WATER_INFODAOImpl(
			Application.getConnection());
		try
		{
		    WATER_INFOObj infoold = dao.findByUPDATETIME(info
			    .getUPDATETIME());
		    if (infoold != null)
		    {
			info.setID(infoold.getID());
			dao.updateObjectByPK(info);
		    } else
		    {
			dao.insertObject(info);
		    }

		    log("OK:" + "操作数据库成功");
		} catch (SQLException e)
		{
		    log("Error:" + "操作数据库失败" + e.getMessage());
		}

	    }
	}
    }

    public WATER_INFOObj parseData(String row)
    {

	String[] cols = row.split(",");

	WATER_INFOObj info = new WATER_INFOObj();
	info.setCOPYRIGHT("珠江水利网");
	info.setSTATION(getItem(cols, 0));
	info.setRIVER(getItem(cols, 1));
	info.setSTAGE(getItem(cols, 2));
	info.setALERT_STAGE(getItem(cols, 3));
	info.setFLUX(getItem(cols, 4));
	info.setMAX_STAGE(getItem(cols, 5));
	info.setTREND(getItem(cols, 6));
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	try
	{
	    info.setUPDATETIME(new Timestamp(df.parse(getItem(cols, 7))
		    .getTime()));
	} catch (ParseException e)
	{
	    e.printStackTrace();
	    info.setUPDATETIME(null);
	}

	return info;

    }

    public String getItem(String[] ds, int index)
    {
	if (index >= 0 && index < ds.length)
	{
	    String r = ds[index];
	    r = r.trim();
	    return r;
	}
	return "";
    }

    public String findRow(String data)
    {
	String r = "";

	int start = data.indexOf("武宣");
	int end = data.indexOf("]", start);
	String str = data.substring(start, end);
	str = str.replaceAll("'", "");

	Pattern p = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);
	Matcher m_style = p.matcher(str);
	str = m_style.replaceAll(""); // 过滤style标签

	str = str.replace("<[^>]+>", "");
	r = str;

	return r;
    }

    public void log(String msg)
    {
	Calendar calendar = Calendar.getInstance();
	System.out.println(format(calendar) + " " + msg);
    }

    private String format(Calendar calendar)
    {
	DateFormat df =new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
	return df.format(new Date(calendar.getTimeInMillis()));

    }

    public String getData()
    {
	String r = "";
	HttpClient client = new HttpClient();

	GetMethod get = new GetMethod(water_url);

	try
	{
	    int code = client.executeMethod(get);
	    if (code == HttpStatus.SC_OK)
	    {
		String script = new String(get.getResponseBody(), "GB2312");
		r = script;
	    }
	} catch (HttpException e)
	{
	    log("Error:" + e.getMessage());
	} catch (IOException e)
	{
	    log("Error:" + e.getMessage());
	}

	log("获取数据成功");
	return r;
    }

    @Override
    public void run()
    {

	this.update();
    }

}
